<template>
  <!-- 添加或编辑对话框 -->
  <el-dialog class="xiaobu-form-dialog" v-bind="$attrs" v-on="$listeners">
    <div v-hasPermi="['system:user:update']" class="edit-box flex-c-e" v-show="baseForm.userId">
      <el-button type="primary" class="edit" @click="toggleEdit">{{
        isEdit ? "取消编辑" : "编辑"
      }}</el-button>
    </div>
    <div class="el-dialog-body-child">
      <el-form class="clearfix" ref="dialogFormRef" :model="dialogForm" :rules="rules"
        :disabled="!!(!isEdit && baseForm.userId)" label-width="120px">
        <el-form-item class="half" label="用户名" prop="userName">
          <el-input v-model.trim="dialogForm.userName" clearable placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item class="half" label="性别" prop="sex">
          <el-select-dict dictType="SEX" v-model="dialogForm.sex" clearable placeholder="请选择性别" />
        </el-form-item>
        <el-form-item v-if="userInfo.userId === 0" class="half" label=" " prop="isEncrypt">
          <div class="content-label four required">接口数据是否加密</div>
          <el-select-dict dictType="YES_NO" v-model="dialogForm.isEncrypt" clearable placeholder="请选择接口数据是否加密" />
        </el-form-item>
        <el-form-item class="half" label="手机号" prop="phoneNumber">
          <el-input v-model.trim="dialogForm.phoneNumber" clearable placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item class="half" label="邮箱" prop="email">
          <el-input v-model.trim="dialogForm.email" clearable placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item class="all" label="备注" prop="remark">
          <el-input type="textarea" v-model="dialogForm.remark" :autosize="{ minRows: 5, maxRows: 8 }" clearable
            placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <template>
        <el-button @click="$emit('close')">{{
          !baseForm.userId || isEdit ? "取 消" : "关 闭"
        }}</el-button>
        <el-button type="primary" @click="submitForm" v-show="!baseForm.userId || isEdit">确 定</el-button>
      </template>
    </div>
  </el-dialog>
</template>
<script>
import { mobileReg, emailReg } from "@/utils/check-reg.js"
import { userApi } from "@/api"
export default {
  name: "UserDialog",
  props: {
    // 是否是编辑
    isUpdate: {
      type: Boolean,
      default: false
    },
    // 配置数据
    baseForm: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {

    const checkUserName = (rule, value, callback) => {
      userApi
        .judgeUserNameExist({ userName: value, userId: this.baseForm.userId })
        .then((data) => {
          if (data.validateResult) {
            callback()
          } else {
            callback(data.msg)
          }
        })
    }

    /** 检查用户名是否已存在 */
    const checkPhoneNum = (rule, value, callback) => {
      userApi
        .judgePhoneNumberExist({ phoneNumber: value, userId: this.baseForm.userId })
        .then((data) => {
          if (data.validateResult) {
            callback()
          } else {
            callback(data.msg)
          }
        })
    }

    /** 检查邮箱是否已存在 */
    const checkEmail = (rule, value, callback) => {
      userApi
        .judgeEmailExist({ email: value, userId: this.baseForm.userId })
        .then((data) => {
          if (data.validateResult) {
            callback()
          } else {
            callback(data.msg)
          }
        })
    }
    return {
      isEdit: false, // 是否是在编辑
      dialogForm: {}, // 弹框表单
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { validator: checkUserName, trigger: "blur" }
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        email: [
          { required: true, message: "请输入邮箱号", trigger: "blur" },
          { pattern: emailReg, message: "请输入正确的邮箱号", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        isEncrypt: [
          { required: true, message: "请选择接口数据是否加密", trigger: "change" }
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: mobileReg,
            message: "请输入正确的手机号",
            trigger: "blur"
          },
          { validator: checkPhoneNum, trigger: "blur" }
        ]
      }
    }
  },
  watch: {
    isUpdate(val) {
      this.isEdit = val
    },
    // 监听baseForm变化 拷贝baseForm
    baseForm: {
      handler: function(val) {
        this.dialogForm = JSON.parse(JSON.stringify(val))
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 编辑或取消编辑
    toggleEdit() {
      if (!this.isEdit) {
        this.isEdit = true
        return
      }
      this.isEdit = false
      this.dialogForm = JSON.parse(JSON.stringify(this.baseForm))
    },
    // 重置表单
    resetForm() {
      this.isEdit = false
      this.$nextTick(() => {
        this.$refs.dialogFormRef.clearValidate()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["dialogFormRef"].validate((valid) => {
        if (valid) {
          //更新
          if (this.dialogForm.userId) {
            userApi.updateItem(this.dialogForm).then((data) => {
              this.$modal.msgSuccess("编辑用户成功")
              this.$emit("close")
              this.$emit("successs")
            })
          } else {
            //新增
            userApi.createItem(this.dialogForm).then((data) => {
              this.$modal.msgSuccess("新增用户成功")
              this.$emit("close")
              this.$emit("successs")
            })
          }
        }
      })
    }
  }
}
</script>
